package com.ljm.shirojwt.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;

public class JwtUtils {
    //过期时间
    private static final long EXPIRE_TIME=5*60*1000;

    /**
     * 校验token
     * @param token
     * @param username 用户名
     * @param secret    密钥
     * @return
     */
    public static boolean verify(String token,String username,String secret){
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier jwtVerifier= JWT.require(algorithm)
                    .withClaim("username",username)
                    .build();
            DecodedJWT jwt=jwtVerifier.verify(token);
            return true;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取用户在token里的信息
     * @param token
     * @return
     */
    public static String getUsername(String token){
        try {
            DecodedJWT jwt=JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成token
     * @param username
     * @param secret
     * @return
     */
    public static String sign(String username,String secret){
        try {
            Date date=new Date(System.currentTimeMillis()+EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            //附带username信息
            return JWT.create()
                    .withClaim("username",username)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
